﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.IO;
using System.Security.Cryptography;

namespace Project_02
{
    public class Avatar
    {
        private Image image;
        private String hash;
        public Avatar() {
            image = null;
            hash = "";
        }
        public Avatar(String file) {
            Stream stream = new FileStream(file, FileMode.Open, FileAccess.Read);
            image = CreateImage(stream, 96, 96);
            hash = GetHash(image);
            stream.Close();
        }
        public Avatar(Stream stream) {
            image = CreateImage(stream, 96, 96);
            hash = GetHash(image);
        }
        public Avatar(Image image) {
            Stream stream = new MemoryStream();
            image.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
            this.image = CreateImage(stream, 96, 96);
            hash = GetHash(this.image);
            stream.Close();
        }
        private Image CreateImage(Stream stream, Int32 w, Int32 h) {
            Image image = Image.FromStream(stream);
            stream.Close();
            if (image.Width == 96 && image.Height == 96) return image;
            Bitmap bitmap = new Bitmap(w, h);
            bitmap.SetResolution(72, 72);
            Graphics graphic = Graphics.FromImage(bitmap);
            graphic.DrawImage(image, new Rectangle(0, 0, w, h), 0, 0, image.Width, image.Height, GraphicsUnit.Pixel);
            stream = new MemoryStream();
            bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
            bitmap.Dispose();
            graphic.Dispose();
            image.Dispose();
            return Image.FromStream(stream);
        }
        public String GetHash(Image image) {
            MD5 md5 = new MD5CryptoServiceProvider();
            String hash = "";
            MemoryStream stream = new MemoryStream();
            image.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
            stream.WriteByte(0xAC);
            foreach (Byte segment in md5.ComputeHash(stream.ToArray())) {
                if (segment < 16) hash += "0";
                hash += segment.ToString("x");
            }
            return hash;
        }
        public Image Image {
            get { return image; }
        }
        public String Hash {
            get { return hash; }
        }
        public Byte[] Data {
            get {
                Stream stream = new MemoryStream();
                image.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
                Byte[] data = new Byte[stream.Length];
                stream.Position = 0;
                while (stream.Position < stream.Length) {
                    data[stream.Position] = (Byte)stream.ReadByte();
                }
                return data;
            }
        }
    }
}
